<?php

namespace App\Library\Logic;

use App\Library\Requests\Base\BasePageRequest;
use App\Models\ShopUserCollectModel;
use Illuminate\Pagination\LengthAwarePaginator;

class ShopUserCollectLogic extends ShopUserCollectModel
{
    /**
     * 分页
     * @param BasePageRequest $request
     * @return array
     */
    public function paging(BasePageRequest $request): array
    {
        $builder = $this->newQuery()->leftJoin('shop_product', 'shop_product.product_id', 'shop_user_collect.uc_source_id')
            ->leftJoin('shop_category', 'shop_category.category_id', 'shop_product.product_category_id_2')
            ->where(['shop_user_collect.user_id' => USERID, 'uc_type' => 1])->orderByDesc('uc_id');
        $paginate = helpBuilder($builder->with('specs'), $request)->paginate($request->limit, [
            'product_id', 'serial_number', 'product_name', 'product_avatar', 'product_status',
            'product_special_start_time', 'product_special_end_time', 'uc_id', 'category_name',
        ]);
        $this->price($paginate);
        return paginate($paginate);
    }

    /**
     * price
     * @param LengthAwarePaginator $paginate
     * @return void
     */
    private function price(LengthAwarePaginator $paginate): void
    {
        foreach ($paginate->items() as $item) {
            $item->price = PHP_INT_MAX;
            $start = now()->gt(now()->timestamp($item->product_special_start_time));
            $end = now()->lt(now()->timestamp($item->product_special_end_time));
            $bool = $start && $end;
            foreach ($item->specs as $v) {
                if ($bool && (float)$v->ps_price > 0) $item->price = min($item->price, $v->ps_price);
                else $item->price = min($item->price, $v->ps_price_underlined);
            }
            unsetObject($item, ['specs', 'product_special_start_time', 'product_special_end_time']);
        }
    }

    /**
     * isFollow
     * @param int $productId
     * @return bool
     */
    public static function isFollow(int $productId): bool
    {
        return self::existsByWhere(['userId' => USERID, 'ucType' => 1, 'ucSourceId' => $productId]);
    }
}
